<template>
  <a-spin :spinning="loading">
    <div class="modal-header">
      <div class="modal-title"
        >{{ l('EditTenant') }} <span v-if="entity">:{{ entity.tenancyName }}</span></div
      >
    </div>
    <div class="modal-body">
      <a-form
        :model="form"
        @submit="handleSubmit"
        ref="formRef"
        :rules="rules"
        :labelAlign="right"
        layout="vertical"
      >
        <!-- 租户名称 -->
        <a-form-item :label="l('TenancyName')" name="name">
          <a-input :placeholder="l('TenancyName')" v-model:value="form.name" />
        </a-form-item>

        <!-- UseHostDatabase -->
        <a-form-item :label="l('DatabaseConnectionString')" v-if="entity.connectionString">
          <a-input
            :placeholder="l('DatabaseConnectionString') + l('Optional')"
            v-model:value="form.databaseConnectionString"
          />
        </a-form-item>

        <!-- 版本 -->
        <a-form-item :label="l('Edition')" has-feedback v-if="isShowEdition">
          <edition-select
            :placeholder="l('PleaseSelect')"
            v-model:value="selectedEdition"
            @change="selectedEditionChange"
          ></edition-select>
        </a-form-item>

        <!-- 是否试用 -->
        <a-checkbox
          @change="checkedChange('isInTrialPeriod', $event)"
          :disabled="IsInTrialPerioddisabled"
          v-model:checked="isInTrialPeriod"
          >{{ l('IsInTrialPeriod') }}</a-checkbox
        >
        <br />

        <!-- 是否激活 -->
        <a-checkbox @change="checkedChange('isActive', $event)" v-model:checked="isActive">
          {{ l('IsActive') }}
        </a-checkbox>

        <a-form-item class="btn--container"> </a-form-item>
      </a-form>
    </div>
    <div class="modal-footer">
      <a-button type="button" @click="close()">
        {{ l('Cancel') }}
      </a-button>
      <a-button type="primary" html-type="submit" @click="handleSubmit($event)">{{
        l('Save')
      }}</a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { ModalComponentBase } from '/@/shared/component-base';
  import { EditionSelect } from '/@/app/admin-shared';
  import { TenantServiceProxy, TenantEditDto } from '/@/shared/service-proxies';
  import { defineComponent } from 'vue';
  export default defineComponent({
    name: 'CreateTenantComponent',
    components: {
      EditionSelect,
    },
    mixins: [ModalComponentBase],
    props: {
      entityId: {
        type: Number,
      },
    },
    data() {
      return {
        confirmDirty: false,
        // 版本
        selectedEdition: [] as any,
        // 是否在试用期
        isInTrialPeriod: false,
        IsInTrialPerioddisabled: false,
        // 下次登录需要修改密码
        shouldChangePasswordOnNextLogin: false,
        // 发送激活邮件
        sendActivationEmail: false,
        // 是否激活
        isActive: true,
        IsUnlimitedchecked: false,
        // IsUnlimited
        isShowIsUnlimited: false,
        // 版本号
        editionId: 0,
        isShowEdition: false,
        // 获取到的数据
        entity: new TenantEditDto(),

        tenantService: new TenantServiceProxy(),
        form: {
          name: '',
          databaseConnectionString: '',
          subscriptionEndUtc: '',
        },
        rules: {
          subscriptionEndUtc: [
            {
              required: true,
              message: this.l('PleaseEnterASubscriptionEndDate'),
            },
          ],
          name: [
            {
              required: true,
              message: this.l('TheTenantDisplayNameCannotBeEmpty'),
              trigger: 'blur',
            },
            {
              min: 3,
              message: this.l('MinLength', 3),
              trigger: 'blur',
            },
            {
              pattern: '^[a-zA-Z][a-zA-Z0-9_-]{1,}$',
              message: this.l(
                'OnlyNumbersAndLettersCanBeEnteredAndTheFirstCharacterCannotBeANumber',
              ),
              trigger: 'blur',
            },
          ],
        },
      };
    },
    mounted() {
      this.getData();
    },
    methods: {
      /**
       * 获取数据
       */
      getData() {
        this.loading = true;
        this.tenantService
          .getForEdit(this.entityId)
          .finally(() => {
            this.loading = false;
          })
          .then((res) => {
            this.entity = res;
            if (!!this.entity.editionId) {
              this.selectedEdition = this.entity.editionId.toString();
            } else {
              this.selectedEdition = null;
            }
            setTimeout(() => {
              this.form.name = this.entity.name;
              (this.form.databaseConnectionString as any) = this.entity.connectionString;
              (this.form.subscriptionEndUtc as any) = this.entity.subscriptionEndUtc;
              this.IsUnlimitedchecked = !this.entity.subscriptionEndUtc;
              this.isActive = this.entity.isActive;
            }, 500);
            this.isShowEdition = true;
          });
      },
      /**
       * 验证密码
       */
      /**
       * 版本选择
       */
      selectedEditionChange(e) {
        if (e && e.value) {
          this.IsInTrialPerioddisabled = true;
          this.isShowIsUnlimited = true;
          this.editionId = parseInt(e.value);
        } else {
          this.IsInTrialPerioddisabled = false;
          this.isShowIsUnlimited = false;
          this.editionId = 0;
        }
      },
      /**
       * 是否试用
       * 下次登录需要修改密码
       * 发送激活邮
       * 是否激活
       */
      checkedChange(type, e) {
        this[`${type}`] = eval(`${e.target.checked}`.toLowerCase()) as never;
      },

      /**
       * 提交表单
       */
      handleSubmit(e) {
        e.preventDefault();
        (this.form.subscriptionEndUtc as any) =
          !this.editionId || this.IsUnlimitedchecked ? null : this.form.subscriptionEndUtc;
        (this.$refs.formRef as any).validate().then(() => {
          let otherobj = {
            isInTrialPeriod: this.isInTrialPeriod,
            isActive: this.isActive,
            editionId: this.editionId == 0 ? null : this.editionId,
            tenancyName: this.entity.tenancyName,
            name: this.form.name,
            connectionString: this.form.databaseConnectionString,
            subscriptionEndUtc: this.form.subscriptionEndUtc,
            id: this.entityId,
          };
          this.loading = true;
          this.tenantService = new TenantServiceProxy(this.$apiUrl, this.$api);
          this.tenantService
            .update(Object.assign(otherobj))
            .finally(() => {
              this.loading = false;
            })
            .then(() => {
              this.notify.success(this.l('SavedSuccessfully'));
              this.success(true);
            });
        });
      },
    },
  });
</script>

<style lang="less" scoped>
  :deep(.btn--container .ant-form-item-children) {
    display: block;
    margin: 10px auto;
    text-align: center;
  }
</style>
